import pymysql

# 路由列表
func_list = {}
# 路由装饰器 向列表中添加数据
def route(data):
    def func_out(func):
        func_list[data] = func
        def func_inner():
            pass
        return func_inner
    return func_out

@route("/index.html")  # 1 @func_out   2 index = func_out(index)
def index():
    with open("./index.html") as f:
        file_data = f.read()

    # 创建链接
    conn = pymysql.connect(host="localhost",
                           port = 3306,
                           database="stock",
                           user="root",
                           password="xsc921101",
                           charset="utf8")
    # 创建游标
    cursor = conn.cursor()

    # 执行sql语句
    sql = "select * from info;"
    cursor.execute(sql)

    # 获取数据
    stock_data = cursor.fetchall()
    print(stock_data)  # 大元组嵌套小元组的形式
    # (1, '00007', '全新好', '10.01%', '4.40%', 'Decimal('16.05'), Decimal('14.60'))
    template = """
        <tr>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>
                <input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="00007">
            </td>
        </tr>
    """
    html = ''
    for i in stock_data:
        html += template %(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7])
    # 模板中的数据替换
    content = file_data.replace("{%content%}", html, 1)

    content = file_data.replace(f"{%content%}", "stock_data", 1)  # 替换1次
    return content

@route("./center.html")
def center():
    with open("./center.html") as f:
        file_data = f.read()
    content = file_data.replace(f"{% content %}", "stock_data", 1)  # 替换1次
    return content
def error():
    return "404 error"
# 向路由列表中添加数据
func_list["/index.html"] = index
func_list["/center.html"] =center
# 列表中的数据
'''
{
    "/index.html": index
    "/center.html": center
}
'''

# 接口 解耦合
def application(req_path):
    # if req_path == "/index.html":
    #     return index()
    # elif req_path == "/center.html":
    #     return center()
    # else:
    #     return error()
    try:
        func = func_list[req_path]
        ret = func()
        return ret
    except Exception as e:
        return error()